<template>
  <div class="my-process-designer">
    <div class="my-process-designer__header">
      <slot name="control-header"></slot>
      <template v-if="!$slots['control-header']">
        <div>
          <el-row style="margin-bottom: 10px;">
            <el-col :span="24" style="text-align: center">
              <el-button size="small" style="margin-top: 5px;" type="text">
                <span :style="styleValue1" @click="switchHandle(0)">{{ buttonValue1 }}</span>
              </el-button>
              <el-button size="small" style="margin-top: 5px;" type="text">
                <span :style="styleValue2" @click="switchHandle(1)">{{ buttonValue2 }}</span>
              </el-button>
              <el-button size="small" style="margin-top: 5px;" type="text">
                <span :style="styleValue3" @click="switchHandle(2)">{{ buttonValue3 }}</span>
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </div>
    <!--审核-->
    <div style="width: 100%;background-color: #F2F4F5;" v-show="this.isAudit !==undefined && isShowType===0">
      <div style="margin-top: 1%;background-color: #ffffff;overflow:auto;">
        <div slot="header" class="clearfix">
          <h4 style="border-left:5px solid #0089ff;padding: 5px;">审批节点</h4>
          <el-button v-if="this.isAudit" size="mini" type="primary" @click="auditHandle(2)"
                     style="margin-left: 30px;"
          >同意
          </el-button>
          <el-button v-if="this.isAudit" size="mini" type="primary" @click="auditHandle(3)"
                     style="margin-left: 30px;"
          >拒绝
          </el-button>
        </div>
        <div style="padding: 10px;">
          <el-steps direction="vertical" :active="isNode" align-center :process-status="processStatus">
            <el-step v-for="(item, index) in stepList" :key="index" :title="item.nodeName"
                     :description="(item.auditState === 0 || item.auditState ===1)
                    ?('审批人:'+item.auditName):('确认人:'+item.verifyUserName+',审批时间:'+item.updateTime)"
            ></el-step>
          </el-steps>
        </div>
      </div>
    </div>
    <!--提交表单-->
    <div style="width: 100%;background-color: #F2F4F5;" v-show="isShowType === 0">
      <div style="height:900px;%;margin-top: 1%;background-color: #ffffff;overflow:auto;">
        <el-form :model="dataFrom">
          <h4 style="border-left:5px solid #0089ff;padding: 5px;">基础信息</h4>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">流程名称:</el-col>
            <el-col :span="16">{{ dataFrom.processName }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">所在业务分类:</el-col>
            <el-col :span="16">{{ dataFrom.businessTypeName }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">主办部门:</el-col>
            <el-col :span="16">{{ dataFrom.hostDeptName }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">责任部门职责:</el-col>
            <el-col :span="16">{{ dataFrom.responsibilityDeptValue }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">基层单位职责:</el-col>
            <el-col :span="16">{{ dataFrom.grassrootsDeptValue }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">横向部门职责:</el-col>
            <el-col :span="16">{{ dataFrom.transverseDeptValue }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">系统名称:</el-col>
            <el-col :span="16">{{ dataFrom.systemName }}</el-col>
          </el-row>
          <el-row style="padding: 5%;border-bottom: 1px solid #dcdfe6;">
            <el-col :span="8" style="font-size: 14px;">系统地址:</el-col>
            <el-col :span="16">{{ dataFrom.systemUrl }}</el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div style="width: 100%;background-color: white;padding-top: 5px;" v-show="isShowType === 2">
      <div v-for="item in fileTable" :key="item.id" @click="getInfo(item)">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>制度名称:{{ item.systemNumber }}</span>
          </div>
          <div class="text item">
            制度编号:{{ item.systemCode }}
          </div>
          <div class="text item">
            制度文号:{{ item.systemNo }}
          </div>
          <div class="text item">
            编制部门:{{ item.superintendent }}
          </div>
          <div class="text item">
            签发日期:{{ item.issueDate }}
          </div>
        </el-card>
      </div>
    </div>
    <el-dialog title="制度文件详情" :visible.sync="institutionInfoOpen" append-to-body width="100%" :fullscreen="true">
      <el-form ref="info" :model="info" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="制度名称:" prop="activityId">
              {{ info.systemNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="制度编号:" prop="event">
              {{ info.systemCode }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="制度文号:" prop="description">
              {{ info.systemNo }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="编制部门:" prop="regulations">
              {{ info.superintendent }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="签发日期:" prop="prohibitedMatter">
              {{ info.issueDate }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="institutionInfoOpen= false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审批" :visible.sync="auditShowOpen" append-to-body width="100%" :fullscreen="true">
      <el-form ref="info" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批意见:">
              <el-input
                size="small"
                v-model="auditText"
                placeholder="请输入审批意见"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="auditShowOpen= false">取 消</el-button>
        <el-button size="small" @click="auditHandleSave">提 交</el-button>
      </div>
    </el-dialog>

    <!--画布-->
    <div class="my-process-designer__container" v-show="isShowType === 1">
      <div class="my-process-designer__canvas" ref="bpmn-canvas-app"></div>
    </div>
  </div>
</template>

<script>
// 生产环境时优化
// const BpmnModeler = window.BpmnJS;
import BpmnModeler from 'bpmn-js/lib/Modeler'
import DefaultEmptyXML from './plugins/defaultEmpty'
// 翻译方法
import customTranslate from './plugins/translate/customTranslate'
import translationsCN from './plugins/translate/zh'
// 模拟流转流程
import tokenSimulation from 'bpmn-js-token-simulation'
// 标签解析构建器
// 标签解析 Moddle
import camundaModdleDescriptor from './plugins/descriptor/camundaDescriptor.json'
import activitiModdleDescriptor from './plugins/descriptor/activitiDescriptor.json'
import flowableModdleDescriptor from './plugins/descriptor/flowableDescriptor.json'
// 标签解析 Extension
import camundaModdleExtension from './plugins/extension-moddle/camunda'
import activitiModdleExtension from './plugins/extension-moddle/activiti'
import flowableModdleExtension from './plugins/extension-moddle/flowable'
// 引入json转换与高亮
import convert from 'xml-js'
import ChooseDept from '@/plugins/package/tree/chooseDept'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import { businessControlTree } from '@/api/lc/business'
import { getProcessInfo2 } from '@/api/workflow/model'
import chooseBusiness from '@/plugins/package/tree/chooseBusiness'
import { deptControlTree2 } from '@/api/system/user'
import { addOrUpdateEvaluateInfo, getScore } from '@/api/lc/evaluation'
import { auditForApp, auditInfoListForApp } from '@/api/lc/processManagementList'

export default {
  name: 'BpmnProcessDesigner',
  componentName: 'BpmnProcessDesigner',
  components: {
    ChooseDept,
    TreeSelect,
    chooseBusiness
  },
  props: {
    value: String, // xml 字符串
    processId: String,
    processName: String,
    translations: Object, // 自定义的翻译文件
    additionalModel: [Object, Array], // 自定义model
    moddleExtension: Object, // 自定义moddle
    onlyCustomizeAddi: {
      type: Boolean,
      default: false
    },
    onlyCustomizeModdle: {
      type: Boolean,
      default: false
    },
    simulation: {
      type: Boolean,
      default: true
    },
    keyboard: {
      type: Boolean,
      default: true
    },
    prefix: {
      type: String,
      default: 'flowable'
    },
    events: {
      type: Array,
      default: () => ['element.click']
    },
    headerButtonSize: {
      type: String,
      default: 'small',
      validator: value => ['default', 'medium', 'small', 'mini'].indexOf(value) !== -1
    },
    headerButtonType: {
      type: String,
      default: 'primary',
      validator: value => ['default', 'primary', 'success', 'warning', 'danger', 'info'].indexOf(value) !== -1
    }
  },
  data() {
    return {
      fileTable: [],
      isAudit: this.$route.params.isAudit,
      isNode: 0,
      stepList: [],
      approveId: this.$route.params.approveId,
      processStatus: '',
      isTabShow: false,
      correlationBaseOpen: false,
      chooseDeptOpen: false,
      defaultZoom: 1,
      previewModelVisible: false,
      simulationStatus: false,
      previewResult: '',
      previewType: 'xml',
      recoverable: false,
      revocable: false,
      styleValue1: 'color: #1890ff;font-size:15px;margin-left: 15px;',
      styleValue2: 'color: #999999;font-size:15px;margin-left: 10px;',
      styleValue3: 'color: #999999;font-size:15px;margin-left: 10px;',
      buttonValue1: '基础设置',
      buttonValue2: '流程设计',
      buttonValue3: '制度文件',
      buttonType: true,
      isShowType: 0,
      dataFrom: {
        processName: '',
        businessTypeId: '',
        businessTypeIds: '',
        businessTypeName: '',
        hostDeptId: '',
        hostDeptIds: '',
        hostDeptName: '',
        responsibilityDeptValue: '',
        grassrootsDeptValue: '',
        transverseDeptValue: '',
        description: '',
        xml: '',
        processAuditType: '',
        systemName: '',
        systemUrl: ''
      },
      hostDeptName: '',
      hostDeptId: '',
      // 树选项
      options: [],
      deptOptions: [],
      businessOptions: [],
      cardDate: [],
      score: 0.00,
      info: {},
      institutionInfoOpen: false,
      auditShowOpen: false,
      auditType: null,
      auditText: null
    }
  },
  computed: {
    additionalModules() {
      const Modules = []
      // 仅保留用户自定义扩展模块
      if (this.onlyCustomizeAddi) {
        if (Object.prototype.toString.call(this.additionalModel) === '[object Array]') {
          return this.additionalModel || []
        }
        return [this.additionalModel]
      }

      // 插入用户自定义扩展模块
      if (Object.prototype.toString.call(this.additionalModel) === '[object Array]') {
        Modules.push(...this.additionalModel)
      } else {
        this.additionalModel && Modules.push(this.additionalModel)
      }
      // 翻译模块
      const TranslateModule = {
        translate: ['value', customTranslate(this.translations || translationsCN)]
      }
      Modules.push(TranslateModule)
      // 模拟流转模块
      if (this.simulation) {
        Modules.push(tokenSimulation)
      }
      if (this.prefix === 'camunda') {
        Modules.push(camundaModdleExtension)
      }
      if (this.prefix === 'flowable') {
        Modules.push(flowableModdleExtension)
      }
      if (this.prefix === 'activiti') {
        Modules.push(activitiModdleExtension)
      }

      return Modules
    },
    moddleExtensions() {
      const Extensions = {}
      // 仅使用用户自定义模块
      if (this.onlyCustomizeModdle) {
        return this.moddleExtension || null
      }

      // 插入用户自定义模块
      if (this.moddleExtension) {
        for (let key in this.moddleExtension) {
          Extensions[key] = this.moddleExtension[key]
        }
      }

      // 根据需要的 "流程类型" 设置 对应的解析文件
      if (this.prefix === 'activiti') {
        Extensions.activiti = activitiModdleDescriptor
      }
      if (this.prefix === 'flowable') {
        Extensions.flowable = flowableModdleDescriptor
      }
      if (this.prefix === 'camunda') {
        Extensions.camunda = camundaModdleDescriptor
      }

      return Extensions
    }
  },
  mounted() {
    this.initBpmnModeler()
    this.createNewDiagram(this.value)
    this.$once('hook:beforeDestroy', () => {
      if (this.bpmnModeler) this.bpmnModeler.destroy()
      this.$emit('destroy', this.bpmnModeler)
      this.bpmnModeler = null
    })
    setTimeout(() => {
      this.isShowType = 1
      this.switchHandle(1)
    }, 500)

    setTimeout(() => {
      this.bpmnModeler.get('canvas').zoom('fit-viewport', 'auto')
    }, 1000)

    setTimeout(() => {
      if (this.$route.params.type === 0 && this.$route.params.isAudit !== true) {
        this.isShowType = 1
        this.switchHandle(1)
      }
    }, 1200)
  },
  created() {
    this.getProcessInfo()
  },
  methods: {
    auditHandle(type) {
      this.auditType = type
      this.auditShowOpen = true
    },
    auditHandleSave() {
      auditForApp({ approveId: this.approveId, type: this.auditType, context: this.auditText }).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'info',
            message: '操作成功'
          })
          this.auditShowOpen = false
        }
      })
    },
    getSetInfo() {
      auditInfoListForApp({ processId: this.dataFrom.processId, processVersion: this.dataFrom.processVersion }).then(res => {
        console.log(res)
        this.stepList = res.data
        for (let i = 0; i < this.stepList.length; i++) {
          if (this.stepList[i].auditState >= 1) {
            if (this.stepList[i].auditState === 3) {
              this.processStatus = 'error'
              this.isNode = i
            } else {
              this.isNode = i
            }
          }
          if (i === this.stepList.length - 1 && this.stepList[i].auditState === 2) {
            this.isNode = i + 1
          }
        }
      })
    },
    add() {
      addOrUpdateEvaluateInfo({
        processId: this.$route.params.id,
        contextJson: JSON.stringify(this.cardDate)
      }).then(res => {
        this.$modal.msgSuccess('操作成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.go(-1)
      })
    },
    cancel() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptControlTree2().then(response => {
        this.deptOptions = response.data
        console.log('this.deptOptions', this.deptOptions)
      })
    },
    /**
     * 流程树
     */
    businessList() {
      businessControlTree().then(response => {
        this.businessOptions = response.data
      })
    },
    // 查询流程信息
    getProcessInfo() {
      let id = this.$route.params.id
      if (id !== undefined && this.$route.params.id !== null && this.$route.params.id !== '') {
        getProcessInfo2(id).then(data => {
          this.dataFrom = data.data
          if (data.data.institution != null) {
            this.fileTable = JSON.parse(data.data.institution)
          }
          this.createNewDiagram(data.data.bpmnXml)
          //this.getScoreInfo()
          if (this.isAudit !== undefined) {
            this.getSetInfo()
          }
        })
      }
    },
    getScoreInfo() {
      getScore(this.$route.params.id).then(res => {
        this.score = res.data
      })
    },
    // 提交保存
    onSave(type) {
      return new Promise((resolve, reject) => {
        if (this.bpmnModeler == null) {
          reject()
        }
        this.bpmnModeler.saveXML({ format: true }).then(({ xml }) => {
          this.dataFrom.xml = xml
          this.dataFrom.processAuditType = type
          this.$emit('save', this.dataFrom)
          resolve(xml)
        })
      })
    },
    // 隐藏基础设置
    hiddenSet(type) {
      const key = document.getElementsByClassName('process-panel__container process-panel')[0]
      if (type === 0) {
        key.setAttribute('hidden', true)
        this.buttonType = false
      } else {
        console.log('显示')
        key.removeAttribute('hidden')
        this.buttonType = true
      }
    },
    // 获取详情
    getInfo(info) {
      this.institutionInfoOpen = true
      this.info = info
    },
    // 切换页面
    switchHandle(type) {
      const key = document.getElementsByClassName('djs-palette two-column open')[0]
      if (key.length !== 0) {
        key.setAttribute('hidden', true)
      }
      this.isShowType = type
      if (type === 0) {
        this.styleValue1 = 'color: #1890ff;font-size:15px;margin-left: 15px;'
        this.styleValue2 = 'color: #999999;font-size:15px;margin-left: 10px;'
        this.styleValue3 = 'color: #999999;font-size:15px;margin-left: 10px;'
        this.buttonValue1 = '基础设置'
        this.buttonValue2 = '流程设计'
        this.buttonValue3 = '制度文件'
      } else if (type === 1) {
        this.styleValue1 = 'color: #999999;font-size:15px;margin-left: 15px;'
        this.styleValue2 = 'color: #1890ff;font-size:15px;margin-left: 10px;'
        this.styleValue3 = 'color: #999999;font-size:15px;margin-left: 10px;'
        this.buttonValue1 = '基础设置'
        this.buttonValue2 = '流程设计'
        this.buttonValue3 = '制度文件'
      } else if (type === 2) {
        this.styleValue1 = 'color: #999999;font-size:15px;margin-left: 15px;'
        this.styleValue2 = 'color: #999999;font-size:15px;margin-left: 10px;'
        this.styleValue3 = 'color: #1890ff;font-size:15px;margin-left: 10px;'
        this.buttonValue1 = '基础设置'
        this.buttonValue2 = '流程设计'
        this.buttonValue3 = '制度文件'
      }
      this.$emit('childShowType', this.isShowType)
    },
    initBpmnModeler() {
      console.log('______0')
      if (this.bpmnModeler) return
      // if (this.$route.params.type === 0 || this.$route.params.type === '0') {
      this.additionalModules.push({
        labelEditingProvider: ['value', ''],
        bendpoints: ['value', {}], //禁用连线拖动
        moveCanvas: ['value', ''], //禁用拖动整个流程图
        move: ['value', ''] //禁用单个图形拖动
        // contextPadProvider: ['value', ''], //禁用图形菜单
        // paletteProvider: ['value', ''], //禁用/清空左侧工具栏
        // labelEditingProvider: ['value', ''], //禁用节点编辑
        // contextPadProvider: ['value', ''], //禁用图形菜单
        // bendpoints: ['value', {}], //禁用连线拖动
        // zoomScroll: ['value', ''], //禁用滚动
        // moveCanvas: ['value', ''], //禁用拖动整个流程图
        // move: ['value', ''] //禁用单个图形拖动
      })
      console.log('______1')
      // }
      this.bpmnModeler = new BpmnModeler({
        container: this.$refs['bpmn-canvas-app'],
        keyboard: this.keyboard ? { bindTo: document } : null,
        additionalModules: this.additionalModules,
        moddleExtensions: this.moddleExtensions
      })
      this.$emit('init-finished', this.bpmnModeler)
      this.initModelListeners()
      this.businessList()
      this.getDeptTree()
    },
    initModelListeners() {
      const EventBus = this.bpmnModeler.get('eventBus')
      const that = this
      // 注册需要的监听事件, 将. 替换为 - , 避免解析异常
      this.events.forEach(event => {
        EventBus.on(event, function(eventObj) {
          let eventName = event.replace(/\./g, '-')
          let element = eventObj ? eventObj.element : null
          that.$emit(eventName, element, eventObj)
          that.$emit('event', eventName, element, eventObj)
        })
      })
      // 监听图形改变返回xml
      EventBus.on('commandStack.changed', async event => {
        try {
          this.recoverable = this.bpmnModeler.get('commandStack').canRedo()
          this.revocable = this.bpmnModeler.get('commandStack').canUndo()
          let { xml } = await this.bpmnModeler.saveXML({ format: true })
          this.$emit('commandStack-changed', event)
          this.$emit('input', xml)
          this.$emit('change', xml)
        } catch (e) {
          console.error(`[Process Designer Warn]: ${e.message || e}`)
        }
      })
      // 监听视图缩放变化
      this.bpmnModeler.on('canvas.viewbox.changed', ({ viewbox }) => {
        this.$emit('canvas-viewbox-changed', { viewbox })
        const { scale } = viewbox
        this.defaultZoom = Math.floor(scale * 100) / 100
      })
    },
    /* 创建新的流程图 */
    async createNewDiagram(xml) {
      // 将字符串转换成图显示出来
      let newId = this.processId || `Process_${new Date().getTime()}`
      let newName = this.processName || `平台流程_${new Date().getTime()}`
      let xmlString = xml || DefaultEmptyXML(newId, newName, this.prefix)
      try {
        let { warnings } = await this.bpmnModeler.importXML(xmlString)
        if (warnings && warnings.length) {
          warnings.forEach(warn => console.warn(warn))
        }
      } catch (e) {
        console.error(`[Process Designer Warn]: ${e.message || e}`)
      }
    },

    // 下载流程图到本地
    async downloadProcess(type, name) {
      try {
        const _this = this
        // 按需要类型创建文件并下载
        if (type === 'xml' || type === 'bpmn') {
          const { err, xml } = await this.bpmnModeler.saveXML()
          // 读取异常时抛出异常
          if (err) {
            console.error(`[Process Designer Warn ]: ${err.message || err}`)
          }
          let { href, filename } = _this.setEncoded(type.toUpperCase(), name, xml)
          downloadFunc(href, filename)
        } else {
          const { err, svg } = await this.bpmnModeler.saveSVG()
          // 读取异常时抛出异常
          if (err) {
            return console.error(err)
          }
          let { href, filename } = _this.setEncoded('SVG', name, svg)
          downloadFunc(href, filename)
        }
      } catch (e) {
        console.error(`[Process Designer Warn ]: ${e.message || e}`)
      }

      // 文件下载方法
      function downloadFunc(href, filename) {
        if (href && filename) {
          let a = document.createElement('a')
          a.download = filename //指定下载的文件名
          a.href = href //  URL对象
          a.click() // 模拟点击
          URL.revokeObjectURL(a.href) // 释放URL 对象
        }
      }
    },

    // 根据所需类型进行转码并返回下载地址
    setEncoded(type, filename = 'diagram', data) {
      const encodedData = encodeURIComponent(data)
      return {
        filename: `${filename}.${type}`,
        href: `data:application/${type === 'svg' ? 'text/xml' : 'bpmn20-xml'};charset=UTF-8,${encodedData}`,
        data: data
      }
    },

    // 加载本地文件
    importLocalFile() {
      const that = this
      const file = this.$refs.refFile.files[0]
      const reader = new FileReader()
      reader.readAsText(file)
      reader.onload = function() {
        let xmlStr = this.result
        that.createNewDiagram(xmlStr)
      }
    },
    /* ------------------------------------------------ refs methods ------------------------------------------------------ */
    downloadProcessAsXml() {
      this.downloadProcess('xml')
    },
    downloadProcessAsBpmn() {
      this.downloadProcess('bpmn')
    },
    downloadProcessAsSvg() {
      this.downloadProcess('svg')
    },
    processSimulation() {
      this.simulationStatus = !this.simulationStatus
      this.simulation && this.bpmnModeler.get('toggleMode').toggleMode()
    },
    processRedo() {
      this.bpmnModeler.get('commandStack').redo()
    },
    processUndo() {
      this.bpmnModeler.get('commandStack').undo()
    },
    // 放大视图
    processZoomIn(zoomStep = 0.1) {
      let newZoom = Math.floor(this.defaultZoom * 100 + zoomStep * 100) / 100
      if (newZoom > 4) {
        throw new Error('[Process Designer Warn ]: The zoom ratio cannot be greater than 4')
      }
      this.defaultZoom = newZoom
      this.bpmnModeler.get('canvas').zoom(this.defaultZoom)
    },
    // 缩小视图
    processZoomOut(zoomStep = 0.1) {
      let newZoom = Math.floor(this.defaultZoom * 100 - zoomStep * 100) / 100
      if (newZoom < 0.2) {
        throw new Error('[Process Designer Warn ]: The zoom ratio cannot be less than 0.2')
      }
      this.defaultZoom = newZoom
      this.bpmnModeler.get('canvas').zoom(this.defaultZoom)
    },
    processZoomTo(newZoom = 1) {
      if (newZoom < 0.2) {
        throw new Error('[Process Designer Warn ]: The zoom ratio cannot be less than 0.2')
      }
      if (newZoom > 4) {
        throw new Error('[Process Designer Warn ]: The zoom ratio cannot be greater than 4')
      }
      this.defaultZoom = newZoom
      this.bpmnModeler.get('canvas').zoom(newZoom)
    },
    // 重置视图并居中
    processReZoom() {
      this.defaultZoom = 1
      this.bpmnModeler.get('canvas').zoom('fit-viewport', 'auto')
    },
    processRestart() {
      this.recoverable = false
      this.revocable = false
      this.createNewDiagram(null).then(() => this.bpmnModeler.get('canvas').zoom(1, 'auto'))
    },
    elementsAlign(align) {
      const Align = this.bpmnModeler.get('alignElements')
      const Selection = this.bpmnModeler.get('selection')
      const SelectedElements = Selection.get()
      if (!SelectedElements || SelectedElements.length <= 1) {
        this.$message.warning('请按住 Ctrl 键选择多个元素对齐')
        return
      }
      this.$confirm('自动对齐可能造成图形变形，是否继续？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => Align.trigger(SelectedElements, align))
    },
    /*-----------------------------    方法结束     ---------------------------------*/
    previewProcessXML() {
      this.bpmnModeler.saveXML({ format: true }).then(({ xml }) => {
        this.previewResult = xml
        this.previewType = 'xml'
        this.previewModelVisible = true
      })
    },
    previewProcessJson() {
      this.bpmnModeler.saveXML({ format: true }).then(({ xml }) => {
        this.previewResult = convert.xml2json(xml, { spaces: 2 })
        this.previewType = 'json'
        this.previewModelVisible = true
      })
    },

    /**
     * 部门弹出
     */
    chooseDeptHandle() {
      this.chooseDeptOpen = true
    },
    /**
     * 部门子页面传参到父页面
     */
    deptValue(data) {
      console.log('部门子页面传参到父页面', data)
      this.hostDeptName = data.label
      this.hostDeptId = data.id
    },
    /**
     * 主办部门选择-确定
     */
    deptSubmitForm() {
      this.dataFrom.hostDeptName = this.hostDeptName
      this.dataFrom.hostDeptId = this.hostDeptId
      this.chooseDeptOpen = false
    },
    /**
     * 主办部门选择-取消
     */
    deptCancel() {
      this.chooseDeptOpen = false
      this.dataFrom.hostDeptName = ''
      this.dataFrom.hostDeptId = ''
    },
    /** 转换结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.businessId,
        label: node.businessName,
        children: node.children
      }
    },
    // 弹出显示
    isDialog() {
      this.correlationBaseOpen = true
    },
    // 子页面回传参数
    checkData(data) {
      this.checkDataValue = data
    },
    /** 关闭按钮 */
    close() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 96%;
  margin: auto;
}

</style>
